// Package avatar -----------------------------
// @file      : avatarAllRoomModel.go
// @author    : WuZhouHai
// @contact   : wzh200x@126.com
// @time      : 2024/7/17 18:20
// @desc      :
// -------------------------------------------
package avatar

import (
	"github.com/gogf/gf/v2/util/gmeta"
	"phoenix/apps/examples/phoenix_app_dwys/defines"
	"phoenix/apps/examples/phoenix_app_dwys/model/gameConfig"
	"phoenix/phoenix/common/logger"
	"phoenix/phoenix/defines/dataType"
	"phoenix/phoenix/entitys/entityModel"
	"phoenix/phoenix/interfaces"
	"phoenix/phoenix/managers/databaseManager"
	"phoenix/phoenix/managers/logicConfigManager"
	"phoenix/phoenix/utils"
)

type AvatarAllRoomModelData struct {
	gmeta.Meta `orm:"table: module_all_room"`
	Dbid       dataType.PhoenixTypeDataBaseId `orm:"id"`
	AvatarId   dataType.PhoenixTypeDataBaseId `orm:"ownerId"`
	UpdateTime string                         `orm:"update_time"`
	RoomId     int32                          `orm:"roomId"` // 店铺类型
	Active     int32                          `orm:"active"` // 是否激活
	Theme      int32                          `orm:"theme"`  // 主题
	Name       string                         `orm:"name"`   // 名称
}

func NewAvatarAllRoomModelData() *AvatarAllRoomModelData {
	return &AvatarAllRoomModelData{}
}

type AvatarAllRoomModel struct {
	entityModel.ModuleModel
}

func (this *AvatarAllRoomModel) LoadModule() error {
	var records []AvatarAllRoomModelData
	err := this.LoadModuleFromDB(&records)
	if err != nil {
		return err
	}
	// 遍历记录
	if len(records) == 0 {
		err := this.Create()
		if err != nil {
			return err
		}
	} else {
		for i, record := range records {
			this.SetModelData(record.Dbid, &records[i])
		}
	}

	return nil
}

func (this *AvatarAllRoomModel) Create() error {
	configs := logicConfigManager.PhoenixManagerLogicConfig().GetConfig(defines.Config_AllRoom)
	base, err := databaseManager.PhoenixManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	for _, config := range configs.GetConfigs().Values() {
		record := config.(*gameConfig.AllRoom)
		if record.Street == 1 {
			data := NewAvatarAllRoomModelData()
			data.AvatarId = this.EntityDBID
			data.RoomId = record.Id
			if record.Id == 2 { // 烧烤店默认激活
				data.Active = 1
			}
			data.Theme = 0
			data.UpdateTime = utils.GetNowTimeFormat()
			data.Name = record.Name
			dataDBid, err := base.GetDb().Model(this.Template).Data(data).OmitEmpty().InsertAndGetId()
			if err != nil {
				logger.PhoenixLoggerIns().Errorf("create AvatarAllRoomModel error %s", err.Error())
			}
			data.Dbid = dataType.PhoenixTypeDataBaseId(dataDBid)
			this.SetModelData(data.Dbid, data)
		}

	}
	logger.PhoenixLoggerIns().Debug("create AvatarAllRoomModel success")
	return nil
}

func NewAvatarAllRoomModel(name string, entityDBID dataType.PhoenixTypeDataBaseId) interfaces.IEntityModuleModel {
	m := &AvatarAllRoomModel{
		ModuleModel: entityModel.NewModuleModel(name, entityDBID),
	}
	m.SetTemplate(NewAvatarAllRoomModelData())
	return m
}
